package com.ideal.controller;

import com.ideal.dto.ResultDto;
import com.ideal.service.IFileService;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
* @Author: lilei
* @Description: 文件接口
* @date: 2022/7/25
*/
@RequestMapping("/api/file")
@Controller
public class FileController {

    private final Logger LOG =  Logger.getLogger(FileController.class);
    @Autowired
    private IFileService fileService;

    @RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
    @ResponseBody
    public ResultDto upload(@RequestParam("configFile") MultipartFile file){
       return  fileService.upload(file);
    }

    /**
     * 文件下载
     * @param request
     * @param response
     * @param configVersionId
     */
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response, Long configVersionId) {

        String versionPath = fileService.findFilePath(configVersionId);
        //response.setContentType("application/octet-stream;charset=UTF-8");
        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment; filename=\"" + versionPath + "\"");
        try(InputStream inputStream = new FileInputStream(versionPath);
            OutputStream os = response.getOutputStream()

        ) {
            //循环写入输出流
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
        }catch (Exception e){
            LOG.error(e.getMessage(),e);
        }
    }
}
